/* 转换tab页 */
<template>
  <div ref="transViewRef" class="transView">
    <!-- 头部 -->
    <div class="u-button-div">
      <el-button
        data-command="zoomOut"
        class="u-button"
        title="缩小"
        icon="el-icon-zoom-out"
        @click="commandHandler('zoomOut')"
      />
      <el-button
        class="u-button"
        data-command="zoomIn"
        title="放大"
        icon="el-icon-zoom-in"
        @click="commandHandler('zoomIn')"
      />
    </div>
    <div class="work-area">
      <!-- 画布 overflow: auto;-->
      <div
        id="graph-container"
        ref="graphContainerRef"
        style="overflow: auto;outline: none"
        :style="{ height: domHeight - bottomHeight + 'px'}"
        class="u-graph-container"
      />
      <div
        ref="outlineRef"
        style="position: absolute; top: 0px; right: 0px; border: solid 1px #c1c1c1; width: 100px; height: 100px;"
      />
    </div>
  </div>
</template>

<script setup lang="ts">

import API from '../../api/index'
import * as studio from '../handler/studio-handler.js'
// 全局常量
import * as global from '../common/common.js'
import tableJson from '../common/trans-metrics-table.json'

let _self = null

import { nextTick, reactive, ref, toRefs, watch, defineEmits, onMounted, h, computed  } from "vue";
import { message, Modal } from 'ant-design-vue';

const state = reactive({
  consoleD: {
    logText: '', // 日志
    metric: [], // 步骤度量字段列
    metricData: [], // 步骤度量列表数据
    execute: null, // 接收定时器
    executeStatus: false // 执行状态
  },
  pluginNameMap: new Map(), // 保存组件名称，用于组件名称重复时的处理
  graph: null, // 保存mxGraph对象
  button: {
    runDisabled: false, // 控制执行按钮点击
    pauseDisabled: true, // 控制暂停按钮点击
    stopDisabled: true // 控制停止按钮点击
  },
  editFlag: false, // 流程修改标记
  executionId: '',
  currentTranStatus: false // 是否是暂停状态
});

const domHeight = computed(()=> {
  return document.documentElement['clientHeight'] - 180
});
const executeStatus = computed(()=> {
  return state.consoleD.executeStatus
})
const bottomHeight = computed(()=> {
  return 80
})

const graphContainerRef = ref();
const outlineRef = ref();
watch(state.consoleD.executeStatus, ()=> {
  clearInterval(state.consoleD.execute)
}, { deep: true })

  onMounted(()=> {
    nextTick(() => {
      init()
    })
  });

  const setGraph = (graph:any) => {
    state.graph = graph
  };
  const setThis = (value:any) => {
    _self = value
  };
  // 执行
  const handleRunClick = async () => {
    // 获取xml
    const xml = await studio.getMxGraphXml(this.graph)
    handlerTransRun(xml)
    // 设置当前标签页不可关闭  执行按钮不可点 停止 暂停按钮可点
    setStatus('run', true, false)
  };
  // 转换执行
  const handlerTransRun = (xml:any) => {
    resetTrans()
    // 根据xml执行转换
    API.trans.run(xml).then(res => {
      const resultStatus = res.status + ''
      if (resultStatus.substring(0, 1) === '2') {
        // 获取执行日志ID
        const executionId = res.data.executionId
        state.executionId = executionId
        if (executionId) {
          // 获取执行结果
          // this.transExecuteResult(executionId);
          // 调用定时器
          transExecuteTimer(executionId)
        } else {
          // 设置当前标签页可关闭  执行按钮可点 停止 暂停按钮置灰不可点
          setStatus('run', false, true)
        }
      } else {
        message.warning(res.data.error.message);
        // 清除定时器
        clearInterval(state.trans.execute)
        // 设置当前标签页可关闭  执行按钮可点 停止 暂停按钮置灰不可点
        setStatus('run', false, true)
      }
    }).catch((error) => {
      state.consoleD.logText = error.message
      // 设置当前标签页可关闭  执行按钮可点 停止 暂停按钮置灰不可点
      setStatus('run', false, true)
    })
  };
  // 获取转换执行结果
  const transExecuteResult = (executionId:any) => {
    const params = {
      executionId: executionId
    }
    API.trans.executeResult(params)
      .then(res => {
      // 执行状态
        state.consoleD.executeStatus = res.data.finished
        // 处理返回的日志数据并显示
        state.consoleD.logText = res.data.logging
        // 处理度量数据并显示
        transMetricDataHandler(res.data.metrics)
        // 显示组件的执行状态
        studio.changePluginState(res.data.status, state.graph)
        // console.log(this.consoleD.executeStatus);
        if (state.consoleD.executeStatus) {
        // 设置当前标签页可关闭  执行按钮可点 停止 暂停按钮置灰不可点
          setStatus('run', false, true)
        }
      })
      .catch(error => {
        const errorResultData = error.response.data
        message.warning(errorResultData.error.message)
        // 清除定时器
        clearInterval(state.consoleD.execute)
        // 设置当前标签页可关闭  执行按钮可点 停止 暂停按钮置灰不可点
        setStatus('run', false, true)
      })
  };
  // 转换调用执行结果定时器
  const transExecuteTimer = (executionId:any) => {
    state.consoleD.execute = window.setInterval(() => {
      transExecuteResult(executionId)
    }, global.METRICS_INTERVAL)
  };
  // 处理转换度量数据
  const transMetricDataHandler = (metricsData:any) => {
    const list = []
    const columns = state.consoleD.metric.columns
    for (let i = 0; i < metricsData.length; i++) {
      const data = metricsData[i]
      const obj = new Object()
      for (let j = 0; j < data.length; j++) {
        obj[columns[j].prop] = data[j]
      }
      list.push(obj)
    }
    // 显示到列表上
    state.consoleD.metricData = list
  };
  /**
   * @param {Object} button 按钮类别 （run, stop, pause）
   * @param {Object} buttonStatus 按钮可点击属性值
   * @param {Object} closeStatus 父组件中tab标签页的关闭属性
   */
  const setStatus = (button:any, buttonStatus:any, closeStatus:any) => {
    // 设置当前标签页可关闭
    _self.tab.active.closable = closeStatus
    if (button === 'run') {
      // 执行按钮可点 停止 暂停按钮置灰
      state.button.runDisabled = buttonStatus
      state.button.pauseDisabled = !buttonStatus
      state.button.stopDisabled = !buttonStatus
    } else if (button === 'stop') {
      state.button.stopDisabled = buttonStatus
      state.button.pauseDisabled = buttonStatus
      state.button.runDisabled = !buttonStatus
    } else if (button === 'pause') {
      state.button.pauseDisabled = buttonStatus
      state.button.stopDisabled = buttonStatus
      state.button.runDisabled = !buttonStatus
    }
  };
  // 重置转换控制台数据
  const resetTrans = async () => {
    // 清空日志
    state.consoleD.logText = ''
    // 清空步骤度量列表数据
    state.consoleD.metricData = []
    // 重置执行状态
    state.consoleD.executeStatus = false
    // 清空组件执行状态图片
    studio.clearPluginOverlays(state.graph)
  };
  // 停止
  const handleStopClick = async () => {
    // 设置执行按钮可点击 停止 暂停按钮不可点 当前标签页可关闭
    await handlerTransStop(state.executionId)
  };
  const handlerTransStop = (executionId:any) => {
    const params = {
      executionId: executionId
    }
    API.trans.stop(params).then(res => {
      console.log(res.data)
    })
  };
  // 暂停
  const handlePauseClick = () => {
    if (!state.currentTranStatus) {
      const params = {
        executionId: state.executionId
      }
      API.trans.pause(params).then(res => {
        const resultStatus = res.status + ''
        if (resultStatus.substring(0, 1) === '2') {
          state.currentTranStatus = true
        }
      })
    } else {
      const params = {
        executionId: state.executionId
      }
      API.trans.resume(params).then(res => {
        const resultStatus = res.status + ''
        if (resultStatus.substring(0, 1) === '2') {
          state.currentTranStatus = false
        }
      })
    }
    setStatus('pause', false, false)
  };
  /**
   * 初始化
   */
  const init = () => {
    state.consoleD.metric = tableJson;
  };
  const commandHandler = (cmd:any) => {
    switch (cmd) {
      case 'zoomOut':
        state.graph.zoomOut()
        break
      case 'zoomIn':
        state.graph.zoomIn()
        break
      default:
        state.graph.editor.execute(cmd)
    }
  };

const transViewRef = ref()
defineExpose({
  graphContainerRef,
  init,
  transViewRef,
  state
})
</script>
<style lang="less" scoped>
.transView {
  display: flex;
  flex-direction: column;
  .u-button-div {
    height: 40px;
    padding: 0 5px 0 5px;
    line-height: 40px;
    .u-button {
      padding: 5px 12px;
    }
  }
  .work-area {
    .u-footer {
      // width: 100%;
      -webkit-margin-end: 5px;
      -moz-margin-end: 13px;
      .el-tabs--border-card {
        height: 100%;
        width: 100%;
        border-left: none;
        .el-tabs__content {
          padding: 6px !important;
        }
      }
      .u-footer-log {
        height: 195px !important;
        // padding-right: 15px;
        .el-textarea__inner {
          height: 195px;
        }
      }
    }
  }
}
</style>
